<template>
	<div>
		<!-- 头部 -->
		<a-form ref="searchRef" :rules="rules" :model="searchForm" :hideRequiredMark="true" style="margin-bottom: 20px">
			<a-row>
				<a-col :span="4" :offset="1">
					<a-form-item name="saleValue" label="状态：">
						<a-select ref="select" v-model:value="searchForm.status" @focus="focus" @change="handleChange"
							placeholder="请选择">
							<a-select-option v-for="item in buyCar" :value="item.id"
								:key="item.id">{{ item.name }}</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4" :offset="1">
					<a-form-item name="saleValue" label="标题">
						<a-input placeholder="根据标题模糊搜索" v-model:value="searchForm.ticketNumOrName"></a-input>
					</a-form-item>
				</a-col>
				<a-col :span="2" :offset="1">
					<a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
				</a-col>
				<a-col :span="2">
					<a-button @click="reset" class="d-a-center">重置</a-button>
				</a-col>
			</a-row>
		</a-form>

		<!-- 列表 -->
		<a-table :columns="columns" :data-source="list" bordered key="id" :loading="loading" :pagination="pagination"
			@change="handleTableChange">
			<!-- :row-selection="rowSelection" -->
			<!-- -->

			<template #title>
				<a-button type="primary" @click="add" v-has="{ a: $route, b: 2 }"
					class="d-a-center">新增</a-button></template>

			<template #joinCrowd="{ record }">
				<div>{{ isAttestStatusList1[record.joinCrowd] }}</div>
			</template>
			<template #grantShape="{ record }">
				<div>{{ fangType2[record.grantShape] }}</div>
			</template>
			<template #useTypeId="{ record }">
				<div>{{ options2[record.useTypeId] }}</div>
			</template>
			<template #faceValueSum="{ record }">
				<div>
					{{
            money1[record.faceValueId] +
            record.faceValueSum +
            (record.faceValueId == 1 ? "元" : "折")
          }}
				</div>
			</template>
			<!-- <template #stack="{ record, index }">
        <div @click="changeStack(record.status, index, record.id)">
          <a-switch
            v-model:checked="record.status"
            :checkedValue="0"
            :unCheckedValue="1"
          />
        </div>
      </template> -->
			<template #operation="{ record }">
				<div class="df">
					<!-- / 1：启用 2：关闭 3：结束 -->
					<a-button type="link" v-if="record.ticketStatusName == '进行中'" @click="
              handleUpdate(record, 2, '停止发行' + record.ticketName + '吗？')
            " v-has="{ a: $route, b: 2 }" class="d-a-center">暂停</a-button>
					<!-- <a-button type="link" @click="edit(record, '编辑')">编辑</a-button> -->
					<a-button type="link" v-if="record.ticketStatusName == '已暂停'" @click="
              handleUpdate(record, 1, '继续发行' + record.ticketName + '吗？')
            " v-has="{ a: $route, b: 2 }" class="d-a-center">继续</a-button>
					<a-button type="link" @click="handleDetail(record, listPage)"
						v-has="{ a: $route, b: 1 }">查看</a-button>

					<a-button type="link" v-if="record.ticketStatusName == '已暂停' && record.useTimeId == 2" @click="
              handleUpdate(record, 3, '结束' + record.ticketName + '吗？')
            " v-has="{ a: $route, b: 2 }" class="d-a-center">结束</a-button>
					<a-button type="link" danger v-if="record.ticketStatusName == '已结束'"
						@click="handleDel(record.key, record.ticketName)" v-has="{ a: $route, b: 2 }"
						class="d-a-center">删除</a-button>
				</div>
			</template>
		</a-table>
		<!-- 多项删除 -->
		<!-- <a-button type="danger" @click="listDel">删除</a-button> -->
	</div>
</template>
<script>
	import {
		reactive,
		ref,
		computed,
		createVNode,
		watch,
		toRefs,
		unref,
		toRaw,
		isReactive,
		toRef,
	} from "vue";
	import router from "@/router/index.js";
	import {
		ports,
		swiperType,
		isAttestStatusList1,
		serviceOptions,
		useOptions,
		options2,
		fangType2,
		money1,
		buyCar,
	} from "@/utils/dict.js";
	import {
		CheckOutlined,
		EditOutlined,
		ExclamationCircleOutlined,
		QuestionCircleOutlined,
	} from "@ant-design/icons-vue";
	import {
		uploadPicture
	} from "@/api/service/index.js";
	import {
		Modal,
		message
	} from "ant-design-vue";
	import {
		PlusOutlined
	} from "@ant-design/icons-vue";
	import *
	as api from "@/api/market/index.js"; // } // deleteConsumableBag, // updateAndAddConsumableBag, // selectAllDetail, // upOrDownConsumableBag, // selectAllConsumableBag, // {
	import {
		selectAllService,
		selectAllType
	} from "@/api/service/index.js";
	import {
		deleteObjBlank
	} from "@/assets/js/common.js";
import { useModal } from "@/hooks"

	export default {
		setup() {
			const searchRef = ref("");
			const formRef = ref("");

			const data = reactive({
				list: [],
				loading: true,
				visible: false,
				serviceList: [], //分类列表
				detaiList: [],
				consumables: [], //默认绑定ID即可
				statusAct: 0,
				searchForm: {},
				typeList: [],
				form: {
					isDele: 0,
					money: 1,
				},
				value: [], //分类-这个远程加载的数据好像不可以哎
				defaultValue: [],
				detailImage: [],
				ports,
				swiperType: true ? [...swiperType.splice(0, 1)] : [...swiperType],
				isAttestStatusList1,
				serviceOptions,
				useOptions,
				options2,
				fangType2,
				money1,
				buyCar,

				listPage: 1,
				toListPage: 1,
			});

			const title = ref(""); //分类名称

			const modalTitle = ref("新增耗材");
			const rules = {
				//  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
				//  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
			};
			const rules1 = {
				name: [{
					required: true,
					message: "请输入耗材名称!",
				}, ],
				sellPrice: [{
					required: true,
					message: "请输入销售价!",
				}, ],
				serviceId: [{
					required: true,
					message: "请输入服务类型!",
				}, ],
				typeId: [{
					required: true,
					message: "请输入服务分类!",
				}, ],
				bazaarPrice: [{
					required: true,
					message: "请输入市场价格!",
				}, ],
				cc: [{
						required: true,
						message: "请输入",
					},
					{
						pattern: /([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/,
						// /^\+?[1-9]\d*$/,
						message: "大于0的正整数",
						trigger: ["change", "blur"],
					},
				],
				// ([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])
				// 大于0的数据

				// value: [{ required: true, message: "请选择耗材分类!" }],
			};

			// 分页器
			const page = reactive({
				pageNum: 1,
				pageSize: 10,
				total: 0,
			});

			const saleStatusOptions = reactive([{
					name: "全部",
					id: "",
				},
				{
					name: "上架",
					id: 0,
				},
				{
					name: "下架",
					id: 1,
				},
			]);
			const consumeOptions = reactive([{
					name: "耗材名称",
					id: 1,
				},
				{
					name: "耗材分类",
					id: 1,
				},
			]);
			const delListId = ref([]); //删除数组ID集合
			const chooseStatus = (status, index) => {
				data.statusAct = index;
				data.searchForm.status = status;
				page.pageNum = 1;
				init();
			};
			// 查询
			const search = () => {
				page.current = 1;
				init();
			};
			const columns = [{
					title: "id",
					dataIndex: "id",
					className: "table",
				},
				{
					title: "编号",
					dataIndex: "ticketNumber",
					className: "table",
				},
				{
					title: "优惠名称",
					dataIndex: "ticketName",
					className: "table",
				},
				{
					title: "参与人群",
					dataIndex: "joinCrowd",
					className: "table",
					slots: {
						customRender: "joinCrowd",
					},
				},
				{
					title: "发放形式",
					dataIndex: "grantShape",
					className: "table",
					slots: {
						customRender: "grantShape",
					},
				},
				{
					title: "使用条件",
					dataIndex: "useTypeId",
					className: "table",
					slots: {
						customRender: "useTypeId",
					},
				},
				{
					title: "面值",
					dataIndex: "faceValueSum",
					className: "table",
					slots: {
						customRender: "faceValueSum",
					},
				},
				{
					title: "创建时间",
					dataIndex: "createdTime",
					className: "table",
				},
				{
					title: "状态",
					dataIndex: "ticketStatusName",
					className: "table",
				},
				{
					title: "操作",
					dataIndex: "operation",
					className: "table",
					slots: {
						customRender: "operation",
					},
				},
			];

			// 分页器
			const pagination = computed(() => ({
				current: page.pageNum,
				pageSize: page.pageSize,
				pageSizeOptions: ["10", "20", "30"],
				showTotal: (total, range) => {
					return "共" + total + "条";
				},
				total: page.total,
				showQuickJumper: true,
				showSizeChanger: true,
			}));

			// 分页器改变的时候
			const handleTableChange = (pagination, filters, sorter) => {
				console.log(pagination, "当前分页");
				page.pageNum = pagination.current;
				page.pageSize = pagination.pageSize;

				// 请求列表接口
				init();
			};
			const cancel = () => {
				data.visible = false;
				title.value = "";
				data.form = {};
				data.consumables = [];
			};
			// 新增
			const add = () => {
				// data.visible = true;
				router.push({
					path: "/market/detail/detail",
				});
			};
			// 查看

			const handleDetail = (item, listPage) => {
				// data.visible = true;
				router.push({
					path: "/market/detail/detail",
					query: {
						item: JSON.stringify(item),
						listPage: listPage,
					},
				});
			};
			const handleUpdateBefore = async (item, name = 1, tip) => {
				// 1：启用 2：关闭 3：结束
				const {closeModal} = useModal.confirm({
					content: () => "你确定要" + tip,
					onOk: async () => {
						handleUpdate(item, name);
						closeModal()
					},
				});
			};
			const handleUpdate = async (item, name = 1) => {
				// 1：启用 2：关闭 3：结束
				let res = await api.operationStatus({
					id: item.id,
					ticketStatus: name,
				});
				if (res.success) {
					message.success("操作成功");
					page.pageNum = 1;
					init();
				}
			};
			const handleEdit = async (item, name = "编辑") => {
				router.push({
					path: "/market/detail/detail",
					id: item.id,
				});
				// item.typeId = String(item.typeId);
				// console.log(item, "item");
				// data.form = item;
				// data.consumables = item.consumables.map((el) => el.id);
				// modalTitle.value = name;
				// data.value[0] = String(item.typeId);
				// data.visible = true;

				// 二级分类
				// let obj = item;
				// item.id = obj.typeId;
				// loadData([item]);
				// let obj = {
				//   pageNum: 1,
				//   pageSize: 80,
				//   typeId: item.typeId,
				// };
				// let res = await selectAllService(obj);
				// if (res.success) {
				//   let index = data.typeList.findIndex((el) => el.id == item.typeId);
				//   console.log(index, "查找到的index是-----");
				//   res.object.records.map((el) => (el.name = el.serveName));
				//   data.typeList[index].children = res.object.records;

				//   data.typeList = [...data.typeList];
				// }
				// data.value[1] = item.serviceId;

				// console.log(data.value, "默认选中的是");
			};
			const Typename = (id) => {
				let item = data.typeList.find((el) => el.id == id);
				console.log(item, "分类名字是");
				return item;
			};

			const serviceName = (id) => {
				let list = data.serviceList.find((el) => el.id == id);
				if (list.serviceName) {
					// return list.serveName;

					return list;
				}
			};

			const closeModal = (e) => {
				data[e] = false;
				if (e == "itemVisible") {
					data.itemForm = {};
				}
				if (e == "visible") {
					data.form = {};
					data.packageList = [];
					data.itemList = [];
				}
			};
			// 删除
			const handleDel = (key, name) => {
				const {closeModal} = useModal.confirm({
					title: () => "你确定删除+ " + name + "+吗?",

					onOk: async () => {
						let res = await api.deleteItem({
							id: key,
						});
						if (res.success) {
							message.success("删除成功");
							init();
							closeModal()
						}
					},

					class: "test",
				});
			};
			const selectConsume = (e) => {
				console.log(e);
			};
			const selectService = (e) => {
				// console.log(e, "服务类型");s
			};
			const selectType = (e) => {};
			// 上传头图
			const uploadDetail_image = (file) => {
				uploadImage(file, "detailImage");
			};
			// 公共的上传图片
			const uploadImage = async (file, e) => {
				let formData = new FormData();
				formData.append("file", file.file);
				let res = await uploadPicture(formData, "ali");
				// // url存入列表中,为什么是两个fileList
				data[e] = data[e].filter((el) => el.status == "done");
				if (res.success) {
					data[e].push({
						uid: file.file.uid,
						url: res.object,
						status: "done",
						name: file.file.name,
					});
				}
				console.log(data[e], "data[e]是--");
			};
			// 全选反选
			const rowSelection = ref({
				checkStrictly: false,
				onChange: (selectedRowKeys, selectedRows) => {
					console.log(
						`selectedRowKeys: ${selectedRowKeys}`,
						"selectedRows: ",
						selectedRows
					);
					delListId.value = selectedRowKeys;
				},
				onSelect: (record, selected, selectedRows) => {
					//console.log(record, selected, selectedRows,'选择多项');
				},
				onSelectAll: (selected, selectedRows, changeRows) => {
					//console.log(selected, selectedRows, changeRows,'全选操作');
					// 数组项
				},
			});

			// 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
			const changeStack = (checked, index, id) => {
				console.log(page.pageNum);
				console.log(checked, index, "是否上下架");
				let title = checked == 0 ? "上架" : "下架";
				// 弹框提示？确定上下架吗
				const {closeModal} = useModal.confirm({
					title: () => `确定${title}当前耗材包吗?`,
					icon: () => createVNode(ExclamationCircleOutlined),
					onOk: async () => {
						let res = await upOrDownConsumableBag(id);
						if (res.success) {
							data.list[index].status = Number(checked);
							closeModal()

						}
					},
					onCancel() {
						let flag = checked == 0 ? 1 : 0;
						data.list[index].status = flag;
						closeModal()
					},
					class: "test",
				});
			};
			initServiceList();
			console.log("router1111111111111", router.options.history.state.forward);
			let detailUrl = router.options.history.state.forward;
			if (detailUrl != null) {
				let detailUrlLength = detailUrl.length;
				let detailUrlLocation = detailUrl.lastIndexOf("=");
				let endData = detailUrl.substr(
					detailUrlLocation + 1,
					detailUrlLength - detailUrlLocation
				);
				if (!endData.startsWith('/market/detail/detail')) {
					data.toListPage = endData;
				}
			}
			console.log("page.current,data.toListPage", page.current, data.toListPage);
			if (data.toListPage != 1) {
				page.pageNum = data.toListPage;
				init();
			} else {
				init();
			}
			async function init() {
				console.log("初始化方法");
				if (data.searchForm.status == 0) {
					delete data.searchForm.status;
				}
				let obj = {
					pageNum: page.pageNum,
					pageSize: page.pageSize,
					...data.searchForm,
				};
				let res = await api.list(obj);
				if (res.success) {
					res.object.list.map((el) => (el.key = el.id));
					// debugger
					// console.log(data.options2,'options2options2options2')
					// let arr = res.object.list.map(m => {
					//   return {
					//     ...m,
					//     grantShape: m.grantShape
					//     // grantShape: data.fangType[m.grantShape].name,
					//     // useTypeId: options2[m.useTypeId].name
					//   }

					// })
					// console.log(arr,'\\\\\\\\')
					data.list = [...res.object.list];
					// data.list.forEach(el=>{
					// })
					data.loading = false;
					page.total = res.object.total;
					data.listPage = res.object.pageNum;
				}
			}
			// 一级分类
			async function initServiceList() {
				let obj = {
					pageNum: 1,
					pageSize: 80,
				};
				let res1 = await selectAllType(obj);
				if (res1.success) {
					res1.object.records.map((el) => (el.isLeaf = false)); //id是string类型的
					data.typeList = res1.object.records;
				}
			}
			// async function initAllDetailList() {
			//   let res = await selectAllDetail();
			//   if (res.success) {
			//     data.detaiList = res.object;
			//   }
			// }

			const loadData = async (selectedOptions) => {
				console.log("点击了选择", selectedOptions);
				const targetOption = selectedOptions[selectedOptions.length - 1];
				targetOption.loading = true; // load options lazily
				let obj = {
					pageNum: 1,
					pageSize: 80,
					typeId: selectedOptions[0].id,
				};
				let res = await selectAllService(obj);
				if (res.success) {
					targetOption.loading = false;
					res.object.records.map((el) => (el.name = el.serveName));
					targetOption.children = res.object.records;

					data.typeList = [...data.typeList];
				}
			};
			const methods = {
				reset() {
					data.searchForm = {};
					page.page = 1;
					init();
				},
			};
			return {
				...toRefs(data),
				...methods,
				saleStatusOptions,
				consumeOptions,
				searchRef,
				modalTitle,
				formRef,
				rules,
				rules1,
				columns,
				pagination,
				title,
				labelCol: {
					style: {
						width: "250px",
					},
				},
				labelCol1: {
					style: {
						width: "150px",
					},
				},
				wrapperCol: {
					span: 20,
				},
				handleTableChange,
				search,
				add,
				handleDel,
				handleUpdateBefore,
				cancel,
				handleEdit,
				rowSelection,
				changeStack,
				serviceName,
				selectConsume,
				selectService,
				chooseStatus,
				Typename,
				selectType,
				loadData,
				uploadDetail_image,
				closeModal,
				handleUpdate,
				handleDetail,
			};
		},

		components: {
			CheckOutlined,
			EditOutlined,
			ExclamationCircleOutlined,
			QuestionCircleOutlined,
			PlusOutlined,
		},
	};
</script>

<style scoped lang="less">
	.act {
		color: #2a9d8f;
	}
</style>